package am.fp
{        
  import fl.controls.ScrollPolicy;
  
  import flash.display.MovieClip;
  import flash.display.Sprite;
  import flash.events.MouseEvent; 

  import com.yahoo.astra.fl.containers.TilePane;
  import com.yahoo.astra.layout.modes.HorizontalAlignment;
  
  import am.fp.Document;
  import am.fp.PageTile;
  import am.fp.FPDispatcher;
  import am.fp.events.StatusEvent;
  import am.fp.events.PageEvent;
  
  /**
   * Page tiles pane. 
   */
  public class TilesContainer extends TilePane
  { 
    // constants
    protected static const TILE_WIDTH: int = 80;
    protected static const TILE_GAP: int = 14;
    protected static const PADDING: int = 11;

    /**
     * Constructor.
     */
    public function TilesContainer()
    {
      // align on middle-center of the tiles and set gap between tiles
      setStyle("skin", "PageSkin");
      tileWidth = TILE_WIDTH;
      paddingTop = paddingBottom = paddingLeft = paddingRight = PADDING;
      horizontalAlign = HorizontalAlignment.CENTER;
      horizontalGap = verticalGap = TILE_GAP;
      horizontalScrollPolicy = ScrollPolicy.OFF;

      // set default width to zero (tiles are hidden)
      width = 0;
      
      // connect listeners
      FPDispatcher.instance.addEventListener(PageEvent.PAGES_COUNT_UPDATED, onPageCountUpdated, false, 0, true);
      FPDispatcher.instance.addEventListener(PageEvent.PAGE_NUM_UPDATED, onPageNumUpdated, false, 0, true);
      FPDispatcher.instance.addEventListener(StatusEvent.CHANGE, onChangeStatus, false, 0, true);
    }

    /**
     * Create tiles when document pages are ready.
     */
    protected function onPageCountUpdated(e: PageEvent): void
    {
      // create tile version of each page
      var doc: Document = Document.instance;
      for (var pageNum: int = 1; pageNum <= doc.pageCount; pageNum++)
        addChild(new PageTile(doc.getPage(pageNum).content, pageNum, tileWidth));
    }
    
    /**
     * Ensure tile for the currently selected page is visible.
     */
    protected function onPageNumUpdated(e: PageEvent): void
    {
      if (e.pageNum <= numChildren)
      {
        var page: PageTile = getChildAt(e.pageNum - 1) as PageTile;
        if (page.y < verticalScrollPosition)
          verticalScrollPosition = page.y + page.height - height + verticalGap;
        else if (page.y + page.height > height + verticalScrollPosition)
          verticalScrollPosition = page.y - verticalGap;
      }
    }

    /**
     * Remove tiles when document is unloaded.
     */
    protected function onChangeStatus(e: StatusEvent): void
    {
      if (e.status == StatusEvent.NO_DOC)
      {
        // remove previous tiles
        while (numChildren > 0)
          removeChild(getChildAt(0));
      }
    }
  }
}
